package com.zuoban.storage.service.impl;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.zuoban.storage.properties.StorageProperties;
import com.zuoban.storage.service.StorageService;
import lombok.RequiredArgsConstructor;

import java.io.InputStream;

/**
 * @BelongsProject: zuoban-boot
 * @BelongsPackage: com.zuoban.storage.service.impl
 * @Author: zxy
 * @CreateTime: 2022-10-10
 * @Description: ...
 */
public class TencentStorageServiceImpl implements StorageService {

    private final StorageProperties storageProperties;
    private final COSCredentials cred;
    private final ClientConfig clientConfig;

    public TencentStorageServiceImpl(StorageProperties storageProperties) {
        this.storageProperties = storageProperties;
        this.cred = new BasicCOSCredentials(storageProperties.getTencent().getAccessKey(), storageProperties.getTencent().getSecretKey());

        this.clientConfig = new ClientConfig(new Region(storageProperties.getTencent().getRegion()));
        this.clientConfig.setHttpProtocol(HttpProtocol.https);
    }

    @Override
    public String upload(InputStream inputStream, String path) {

        try {
            COSClient cosClient = new COSClient(cred, clientConfig);

            // 存储桶名称，格式：BucketName-APPID
            String bucketName = storageProperties.getTencent().getBucketName() + "-" + storageProperties.getTencent().getAppId();

            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(inputStream.available());

            PutObjectRequest request = new PutObjectRequest(bucketName, path, inputStream, metadata);
            PutObjectResult result = cosClient.putObject(request);

            cosClient.shutdown();
            if (result.getETag() == null) {
                throw new RuntimeException("上传文件失败，请检查配置信息");
            }
        } catch (Exception e) {
            throw new RuntimeException("上传文件失败：", e);
        }

        return storageProperties.getConfig().getDomain() + "/" + path;
    }
}
